﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpAlgorithm
{
    class Survivor2
    {
        public Survivor2()
        {
            int testCount = Int32.Parse(TestConsole.ReadLine());

            for (int testCase = 1; testCase <= testCount; testCase++)
            {
                int foodCount = Int32.Parse(TestConsole.ReadLine());
                List<int[]> foodList = new List<int[]>();
                for (int i = 1; i <= foodCount; i++)
                {
                    string[] input = TestConsole.ReadLine().Split(' ');
                    int start = Int32.Parse(input[0]);
                    int delay = Int32.Parse(input[1]);
                    int end = start + delay;
                    foodList.Add(new int[3] { start, delay, end });
                }
                foodList = foodList.OrderBy(f => f[2]).ToList();
                List<int[]> eatList = new List<int[]>();
                int time = 0;
                for (int i = 0; i < foodList.Count; i++)
                {
                    int[] now = foodList[i]; //먹을 후보
                    if (time <= now[0]) //그냥 먹으면 됨
                    {
                        eatList.Add(now);
                        time += now[1];
                    }
                    else
                    {
                        int needTime = time - now[0];
                        List<int[]> delList = eatList.OrderBy(f => f[1]).ToList();//대신 포기해야 할 리스트
                        for (int j = 0; j < delList.Count; j++)
                        {
                            needTime -= delList[j][1];
                            if (needTime <= 0)
                            {
                                delList.RemoveRange(0, j + 1);
                                delList.Add(now);
                                int newTime = delList.Sum(f => f[1]);
                                if (newTime > time)
                                {
                                    eatList = delList;
                                    time = newTime;
                                }
                                break;
                            }
                        }

                    }

                }
                Console.WriteLine("Case #" + testCase + ": " + time);
            }
        }
    }
}
